<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import request, { SERVER_BASE_URL } from "@/utils/request.js"

// 路由实例
const router = useRouter()

// 用户ID
const userId = ref(null)
// 订单列表
const orderList = ref([])
// 当前激活的标签页
const activeTab = ref('all')
// 加载状态
const loading = ref(false)

// 检查登录状态
const checkLoginStatus = () => {
  const userInfo = JSON.parse(localStorage.getItem('user'))
  if (!userInfo) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return false
  }
  
  userId.value = userInfo.id
  return true
}

// 获取订单列表
const getOrderList = async (status = '') => {
  if (!checkLoginStatus()) return
  
  loading.value = true
  try {
    let url = '/order/list'
    if (status) {
      // 如果有特定状态的API，则使用特定的API
      switch (status) {
        case 'PENDING_PAYMENT':
          url = '/order/pending-payment'
          break
        case 'PAID':
          url = '/order/paid'
          break
        case 'SHIPPED':
          url = '/order/shipped'
          break
        case 'COMPLETED':
          url = '/order/completed'
          break
        case 'CANCELLED':
          url = '/order/cancelled'
          break
      }
    }
    
    const res = await request.get(url, {
      params: { userId: userId.value, status: status || undefined }
    })

    console.log(res)

    if (res.code === 200) {
      orderList.value = res.data
    } else {
      ElMessage.error(res.message || '获取订单列表失败')
    }
  } catch (error) {
    console.error('获取订单列表失败:', error)
    ElMessage.error('获取订单列表失败')
  } finally {
    loading.value = false
  }
}

// 处理标签页切换
const handleTabChange = (tab) => {
  activeTab.value = tab
  
  // 根据标签获取对应状态的订单
  switch (tab) {
    case 'all':
      getOrderList()
      break
    case 'pending-payment':
      getOrderList('PENDING_PAYMENT')
      break
    case 'paid':
      getOrderList('PAID')
      break
    case 'shipped':
      getOrderList('SHIPPED')
      break
    case 'completed':
      getOrderList('COMPLETED')
      break
    case 'cancelled':
      getOrderList('CANCELLED')
      break
  }
}

// 查看订单详情
const viewOrderDetail = (orderNo) => {
  router.push(`/order/${orderNo}`)
}

// 取消订单
const cancelOrder = async (order) => {
  if (!checkLoginStatus()) return
  
  try {
    const res = await request.put(`/order/cancel/${order.id}`)
    if (res.code === 200) {
      ElMessage.success('订单取消成功')
      // 刷新当前标签页的订单列表
      handleTabChange(activeTab.value)
    } else {
      ElMessage.error(res.message || '取消订单失败')
    }
  } catch (error) {
    console.error('取消订单失败:', error)
    ElMessage.error('取消订单失败')
  }
}

// 确认收货
const completeOrder = async (order) => {
  if (!checkLoginStatus()) return
  
  try {
    const res = await request.put(`/order/complete/${order.id}`)
    if (res.code === 200) {
      ElMessage.success('确认收货成功')
      // 刷新当前标签页的订单列表
      handleTabChange(activeTab.value)
    } else {
      ElMessage.error(res.message || '确认收货失败')
    }
  } catch (error) {
    console.error('确认收货失败:', error)
    ElMessage.error('确认收货失败')
  }
}

// 支付订单（跳转到订单详情页）
const payOrder = (orderNo) => {
  router.push(`/order/${orderNo}`)
}

// 处理图片URL
const getImgUrl = (url) => {
  if (!url) return '';

  // 确保有服务器地址前缀
  let fullUrl = url;
  if (url.startsWith('/uploads/')) {
    fullUrl = SERVER_BASE_URL + url;
  }

  return fullUrl;
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '-'
  const date = new Date(dateString)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
}

// 订单状态中文名称
const getStatusText = (status) => {
  const statusMap = {
    'PENDING_PAYMENT': '待付款',
    'PAID': '已付款',
    'SHIPPED': '已发货',
    'COMPLETED': '已完成',
    'CANCELLED': '已取消'
  }
  return statusMap[status] || status
}

// 获取订单状态标签类型
const getStatusTagType = (status) => {
  const typeMap = {
    'PENDING_PAYMENT': 'warning',
    'PAID': 'success',
    'SHIPPED': 'primary',
    'COMPLETED': 'success',
    'CANCELLED': 'info'
  }
  return typeMap[status] || ''
}

// 页面加载时获取所有订单
onMounted(() => {
  getOrderList()
})
</script>

<template>
  <div class="orders-container">
    <el-card class="orders-card">
      <div class="orders-header">
        <h2>我的订单</h2>
      </div>

      <el-tabs v-model="activeTab" @tab-click="(tab) => handleTabChange(tab.props.name)" type="card">
        <el-tab-pane label="全部订单" name="all"></el-tab-pane>
        <el-tab-pane label="待付款" name="pending-payment"></el-tab-pane>
        <el-tab-pane label="待发货" name="paid"></el-tab-pane>
        <el-tab-pane label="待收货" name="shipped"></el-tab-pane>
        <el-tab-pane label="已完成" name="completed"></el-tab-pane>
        <el-tab-pane label="已取消" name="cancelled"></el-tab-pane>
      </el-tabs>

      <div class="orders-content" v-loading="loading">
        <div v-if="orderList.length === 0" class="empty-orders">
          <el-empty description="暂无订单数据"></el-empty>
        </div>

        <div v-else class="order-list">
          <el-card v-for="order in orderList" :key="order.id" class="order-item">
            <div class="order-header">
              <div class="order-info">
                <span class="order-number">订单号：{{ order.orderNo }}</span>
                <span class="order-date">下单时间：{{ formatDate(order.createTime) }}</span>
              </div>
              <el-tag :type="getStatusTagType(order.status)">{{ getStatusText(order.status) }}</el-tag>
            </div>

            <div class="order-products">
              <div v-for="(item, index) in order.orderItems" :key="index" class="product-item">
                <el-image
                  :src="item.image && item.image.length > 0 ? getImgUrl(item.image[0]) : ''"
                  fit="cover"
                  class="product-image"
                ></el-image>
                <div class="product-info">
                  <div class="product-name">{{ item.commodityName }}</div>
                  <div class="product-price-qty">
                    <span class="product-price">¥{{ item.commodityPrice }}</span>
                    <span class="product-qty">x{{ item.quantity }}</span>
                  </div>
                </div>
              </div>
            </div>

            <div class="order-footer">
              <div class="order-amount">
                <span>共 {{ order.orderItems ? order.orderItems.length : 0 }} 件商品，</span>
                <span>实付：<strong class="price">¥{{ order.actualAmount }}</strong></span>
              </div>

              <div class="order-actions">
                <el-button type="primary" size="small" @click="viewOrderDetail(order.orderNo)">查看详情</el-button>

                <!-- 待付款状态 -->
                <template v-if="order.status === 'PENDING_PAYMENT'">
                  <el-button type="danger" size="small" @click="cancelOrder(order)">取消订单</el-button>
                  <el-button type="success" size="small" @click="payOrder(order.orderNo)">去支付</el-button>
                </template>

                <!-- 待收货状态 -->
                <template v-if="order.status === 'SHIPPED'">
                  <el-button type="success" size="small" @click="completeOrder(order)">确认收货</el-button>
                </template>
              </div>
            </div>
          </el-card>
        </div>
      </div>
    </el-card>
  </div>
</template>

<style scoped>
.orders-container {
  padding: 20px;
}

.orders-card {
  border-radius: 12px;
  min-height: 80vh;
}

.orders-header {
  margin-bottom: 20px;
}

.orders-header h2 {
  margin: 0;
  font-size: 20px;
  color: #333;
}

.orders-content {
  min-height: 300px;
}

.empty-orders {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 300px;
}

.order-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.order-item {
  border-radius: 8px;
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 15px;
  border-bottom: 1px solid #f0f0f0;
  margin-bottom: 15px;
}

.order-info {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.order-number, .order-date {
  color: #606266;
  font-size: 14px;
}

.order-products {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  margin-bottom: 15px;
}

.product-item {
  display: flex;
  align-items: center;
  width: 250px;
}

.product-image {
  width: 60px;
  height: 60px;
  border-radius: 4px;
  margin-right: 10px;
}

.product-info {
  flex: 1;
  min-width: 0;
}

.product-name {
  margin-bottom: 5px;
  font-size: 14px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.product-price-qty {
  display: flex;
  justify-content: space-between;
  color: #606266;
  font-size: 14px;
}

.product-price {
  color: #f56c6c;
}

.order-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 15px;
  border-top: 1px solid #f0f0f0;
}

.order-amount {
  color: #606266;
  font-size: 14px;
}

.price {
  color: #f56c6c;
  font-size: 16px;
}

.order-actions {
  display: flex;
  gap: 10px;
}
</style> 